<template>
    <div class="silder-right">
        <div id="listRightTip" ref="listRightTip" class="list-right">
            <div class="list-right-div">
                <el-button type="primary" size="mini" @click="queryPopupVisible = true">查询</el-button>
                <el-button type="primary" size="mini" @click="refreshBtn">刷新</el-button>
                <el-button type="primary" size="mini" @click="editBtn(currentNode.id)">编辑</el-button>
                <el-button type="danger" size="mini" @click="moveBtn(currentNode.id)">{{
                    currentNode.id == '1' ? '移入黑名单' : '移入白名单'
                }}</el-button>
                <el-button type="primary" size="mini" @click="loadoutBtn(currentNode.id)">导出</el-button>
            </div>
            <div style="width: 100%; height:calc(100vh - 135px); margin: 0 auto;">
                <RiskTable
                    ref="risk-table"
                    :tableData="currentTableData"
                    :tableConfig="tableConfig"
                    :column="columns"
                    :paging="paging"
                    :searchParams="searchParams"
                    @page-change="pageChange"
                    @getAllData="getRightAllData"
                    v-loading="tableLoading"
                    :key="tableKey"
                >
                    <template #operation="{ row }">
                        <RiskIconButton
                            type="primary"
                            icon="el-icon-right"
                            :topTitle="currentNode.id == '1' ? '移入黑名单' : '移入白名单'"
                            v-authCode="B_0191"
                            @on-click="delClauseDialog(row, '单个解除')"
                        ></RiskIconButton>
                    </template>
                </RiskTable>
            </div>
        </div>
        <template>
            <!-- 编辑 -->
            <EditEntryPopup
                :editEntryPopupVisible="editEntryPopupVisible"
                :currentNode="currentNode"
                @emitEditEntryPopupVisible="emitEditEntryPopupVisible"
            ></EditEntryPopup>
        </template>
        <!-- 查询弹框 -->
        <yh-dialog
            :title="currentNode.id === '1' ? '查询白名单条目' : '查询黑名单条目'"
            :visible.sync="queryPopupVisible"
            width="400px"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            drag
        >
            <el-form label-width="100px" style="width:100%;">
                <el-row>
                    <el-form-item label="条目编码：">
                        <el-input v-model="searchParams.entryCode" size="mini"></el-input>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="风险说明：">
                        <el-input v-model="searchParams.entryName" size="mini"></el-input>
                    </el-form-item>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleBtn('cancel')" :loading="queryLoading">取 消</el-button>
                <el-button @click="handleBtn('reset')" :loading="queryLoading">重 置</el-button>
                <el-button type="primary" @click="handleBtn('confirm')" :loading="queryLoading">确 定</el-button>
            </span>
        </yh-dialog>
        <!-- 移除 -->

        <yh-dialog :visible.sync="removeDialog" width="700px" :close-on-click-modal="false" :close-on-press-escape="false" drag>
            <template slot="title">
                <span v-html="getRemoveTitle()" style="color:#fff"></span>
            </template>
            <div>
                <p>{{ removeInfo.noExistsEntryCode || '--' }}</p>
            </div>
            <el-divider></el-divider>
            <div>
                {{ (currentNode.id == '1' ? '黑' : '白') + '名单已存在条目:' }}
                <p style="display:inline-block">{{ removeInfo.existsEntryCode || '--' }}</p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="removeDialog = false" :loading="removeLoading">取 消</el-button>
                <el-button size="mini" type="primary" @click="moveDialogConfirm" :loading="removeLoading">确 定</el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Prop, Model, Emit, Vue, Watch } from 'vue-property-decorator';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { UUID, timeFormat, numberFormat, unitShow, dateFormat, getCurrentPageData } from '@/utils/tools';
import QueryPopup from './query-popup.vue';
import EditEntryPopup from './edit-entry-popup.vue';
import RiskTable from '@/common/components/risk-table-plus.vue';
import { VueObject, PageVO, ColumnVO, TableConfigVO } from '@/common/vo';
import { compareSyncLmtEntryCode, getBlackWhite, handleImmigraTion, selectByEntryCode } from '@/pages/setting/api';
import { downLoadFile } from '@/utils/request';

@Component({
    name: 'WhiteListDetail',
    components: {
        RiskIconButton,
        RiskPagination,
        QueryPopup,
        EditEntryPopup,
        RiskTable,
    },
})
export default class WhiteListDetail extends Vue {
    @Prop() currentNode; // 当前状态：白名单/黑名单

    tableData: any[] = [];
    tableKey: number = 0;
    paging: PageVO = { total: 0, currentPage: 1, pageSize: 25 };
    columns: ColumnVO[] = [
        {
            type: 'checkbox', // 复选框
            selectedAll: true, // 选中所有页
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '条目编号',
            field: 'entryCode',
            sortable: true,
            sortField: 'L_SERIAL_NO',
            // fixed: 'left',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 130,
        },
        {
            title: '风险说明',
            field: 'entryName',
            sortable: true,
            sortField: 'VC_SUMMARY',
            filters: [{ data: '' }],
            filterType: 'search',
            minWidth: 250,
            style: (value, record) => {
                if (record.isDeleted === '0') {
                    return { color: 'red' };
                }
            },
        },
        {
            title: '操作',
            field: 'operation',
            fixed: 'right',
            width: 90,
            align: 'center',
        },
    ];
    tableConfig: TableConfigVO = {
        rowKey: 'entryCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableLoading: boolean = false;
    searchParams: any = {
        entryCode: '',
        entryName: '',
    };
    sort: string = '';
    queryPopupVisible: boolean = false;
    editEntryPopupVisible: boolean = false;
    removeDialog: boolean = false;
    removeLoading: boolean = false;
    queryLoading: boolean = false;
    currentTableData: any = [];

    @Watch('currentNode.id', { immediate: true, deep: true })
    watchCurrentNode(newData, oldData) {
        this.tableKey++; // 重置筛选和排序条件
        this.handleReset();
        this.$nextTick(() => {
            (this.$refs['risk-table'] as any).resetCheckRowKeys();
        });
        this.getBlackWhiteList();
    }

    /**
     * 获取黑白名单列表
     */
    getBlackWhiteList(type?: string): void {
        this.tableLoading = true;
        getBlackWhite({ ...this.searchParams, lmtType: String(this.currentNode.id) })
            .then(res => {
                this.tableLoading = false;
                this.tableData = res;
                this.getTableData();
                this.paging.total = res?.length;
                type == 'query' && (this.queryPopupVisible = false);
                type == 'refresh' && this.yh_message_success('已刷新成功！');
            })
            .catch(res => {})
            .finally(() => {
                this.tableLoading = false;
                type == 'query' && (this.queryLoading = false);
            });
    }

    pageChange(type?: string) {
        this.getTableData();
        if (type == 'filter') {
            this.getBlackWhiteList();
        }
    }

    // 前端处理排序和分页
    getTableData(): any {
        let data = [];
        const tempArr = this.tableData;
        const sort = this.searchParams.sort && this.searchParams.sort.split(' ');
        if (sort) {
            if (sort[0] == 'L_SERIAL_NO') {
                data = tempArr.slice().sort(this.sortBy('entryCode', sort[1]));
            } else if (sort[0] == 'VC_SUMMARY') {
                data = tempArr.slice().sort(this.compare('entryName', sort[1]));
            }
        } else {
            data = tempArr;
        }
        this.paging.total = tempArr.length;
        const retData = getCurrentPageData(data, this.paging.currentPage, this.paging.pageSize);
        this.currentTableData = retData;
    }

    /**
     * 对象数组排序
     * @param sortBy 排序字段
     * @param sortType 排序方式
     */
    sortBy(props, sortType) {
        return function(a, b) {
            const num1 = a[props].replace(/[^\d]/g, '');
            const num2 = b[props].replace(/[^\d]/g, '');
            if (sortType.toUpperCase() == 'DESC') {
                return num2 - num1;
            } else {
                return num1 - num2;
            }
        };
    }

    /**
     * 比较函数
     * @param  {string} prop 数据里面要排序的key
     * @param  {number} type 1:asc  -1:desc
     * @return {number}
     */
    private compare(prop, type) {
        return function(obj1, obj2) {
            if (type == 'ASC') {
                return obj1[prop].localeCompare(obj2[prop], 'zh-CN', { numeric: true });
            } else if (type == 'DESC') {
                return obj2[prop].localeCompare(obj1[prop], 'zh-CN', { numeric: true });
            }
        };
    }

    /**
     * 重置按钮事件
     */
    handleReset(): void {
        this.searchParams = {
            entryCode: '',
            entryName: '',
        };
        this.paging = { total: 0, currentPage: 1, pageSize: 25 };
    }

    /**
     * 右侧的所有数据
     */
    getRightAllData() {
        getBlackWhite({
            ...this.searchParams,
            lmtType: String(this.currentNode.id),
            paging: {
                currentPage: 1,
                pageSize: 10000,
            },
        })
            .then((res: any) => {
                this.tableConfig.allRowKeys = res.map(item => item.entryCode);
                (this.$refs['risk-table'] as any).handleSelectAll();
            })
            .catch(err => {
                console.log(err);
            });
    }

    handleBtn(param): void {
        if (param == 'cancel') {
            this.queryPopupVisible = false;
        }
        if (param == 'confirm') {
            this.queryLoading = true;
            this.paging.currentPage = 1;
            this.getBlackWhiteList('query');
            for (const key in this.searchParams) {
                this.handleTableHeaderColumns(key);
            }
        }
        if (param == 'reset') {
            this.handleReset();
        }
    }

    // 查询条件同步表头
    handleTableHeaderColumns(key: string) {
        const $table = this.$refs['risk-table'] as any;
        const $xTable = $table.$refs['xTable'];
        const column = $xTable.getColumnByField(key);
        if (column) {
            const option = column.filters[0];
            const value = this.searchParams[key];
            option.data = value;
            option.checked = !!value;
        }
    }

    // 编辑Btn
    editBtn(param) {
        this.editEntryPopupVisible = true;
    }

    // 刷新
    refreshBtn() {
        this.paging.currentPage = 1;
        this.getBlackWhiteList('refresh');
    }

    // 移入黑白名单Btn
    moveBtn(param) {
        const keys = (this.$refs['risk-table'] as any).checkRowKeys;
        if (keys.length < 1) {
            this.yh_message_warn('请先勾选待处理的条目!');
            return;
        }
        this.del(keys);
    }

    loadoutBtn(param) {
        const keys = (this.$refs['risk-table'] as any).checkRowKeys || [];
        downLoadFile({
            url: '/syncLmtCode/export/entryCode',
            method: 'post',
            data: {
                lmtType: String(this.currentNode.id),
                excelEntryCode: keys,
            },
        });
    }
    removeInfo = {
        existsEntryCode: '',
        noExistsEntryCode: '',
        // noExistsEntryCodes: [],
    };
    selectEntryCodes: any[] = [];

    // 单个移除
    delClauseDialog(row: any) {
        this.del([row.entryCode]);
    }

    del(codes: any) {
        compareSyncLmtEntryCode({
            noExistsEntryCodes: codes,
            // 目标类型
            lmtType: this.currentNode.id == '1' ? '2' : '1',
        }).then((res: any) => {
            console.log(res, 'res');
            this.removeDialog = true;
            this.removeInfo.existsEntryCode = res.existsEntryCode;
            this.removeInfo.noExistsEntryCode = res.noExistsEntryCode;
            // this.removeInfo.noExistsEntryCodes = res.noExistsEntryCodes;

            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        });
    }

    // 移入x名单->确认
    moveDialogConfirm() {
        this.removeLoading = true;
        const id = this.currentNode.id;
        const targetType = id == '1' ? '2' : '1';
        const typeCode = id == '1' ? '9' : '10';
        const entryCodes = this.removeInfo.noExistsEntryCode ? this.removeInfo.noExistsEntryCode.split(',') : [];
        handleImmigraTion({
            lmtType: this.currentNode.id,
            targetType,
            entryCodes,
            typeCode,
            existsEntryCode: this.removeInfo.existsEntryCode || '',
        })
            .then((res: any) => {
                console.log(res, '---');
                this.yh_message_success(`移入${targetType == '1' ? '白名单' : '黑名单'}成功`);
                this.paging.currentPage = 1;
                this.getBlackWhiteList();
                this.$nextTick(() => {
                    const entryCode = this.removeInfo.existsEntryCode || this.removeInfo.noExistsEntryCode;
                    (this.$refs['risk-table'] as any).checkboxChange({ checked: false, row: { entryCode: entryCode } });
                });
            })
            .catch(err => {
                console.log(err);
            })
            .finally(() => {
                this.removeDialog = false;
                this.removeLoading = false;
            });
    }

    thresholdTypeFormat(value, unit): string {
        // 三目运算符, unit为'%'和'万元'、'万股'的由后端处理了，不由numberFormat方法处理
        return ['%', '万元', '万股'].includes(unit) ? value : numberFormat(value.replace(/[^0-9.]/gi, ''), unit) + unitShow(unit);
    }

    emitEditEntryPopupVisible(param) {
        this.editEntryPopupVisible = false;
        this.paging.currentPage = 1;
        if (param == 'confirm') {
            this.getBlackWhiteList();
            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        }
    }

    getRemoveTitle() {
        const value1 = this.currentNode.id == '1' ? '白' : '黑';
        const value2 = this.currentNode.id == '1' ? '黑' : '白';
        return `<span>确定将以下条目从${value1}名单移入到${value2}名单吗？</span>
            <span style="font-size:12px">(已自动过滤${value2}名单中已存在的条目,会将其直接从${value1}名单中删除</span>)`;
    }
}
</script>
<style lang="scss" scoped>
.list-right {
    background: #fff;
    // border: 1px solid #cacaca;
    width: 100%;

    .list-right-div {
        // border-bottom: 1px solid #cacaca;
        padding: 4px 10px;
        width: 100%;
    }
}
</style>
